#include <opencv4/opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include "capset/myVideoCap.h"
#include <stdio.h>

// #define VIDEO_SAVE

int main(int argc, char* argv[]) {
    bool saveFrames=false, saveVideo=false;
    char device[20];
    sprintf(device, "/dev/video0");
    if(argc > 1) {
        for(unsigned int i=1; i<argc; i++) {
            std::string arg = argv[i];
            if(arg == "-help" || arg == "-h") {
                std::cout << "Usage" << std::endl;
                std::cout << "\t-frames: Save frames not video." << std::endl;
                std::cout << "\t-video: Save video not frames." << std::endl;
                std::cout << "\t-device: Set device. (default: /dev/video0)." << std::endl;
                return 0;
            }
            else if(arg == "-frames") {
                saveFrames = true;
                if(saveVideo) {
                    std::cout << "Bad args." << std::endl;
                    std::cout << "\tUse \n\t`./tool -help|-h` \n\tto get further information" << std::endl;
                    return -1;
                }
            }
            else if(arg == "-video") {
                saveVideo = true;
                if(saveFrames) {
                    std::cout << "Bad args." << std::endl;
                    std::cout << "\tUse \n\t`./tool -help|-h` \n\tto get further information" << std::endl;
                    return -1;
                }
            }
            else if(arg == "-device") {
                i++;
                if(i<argc) {
                    sprintf(device, argv[i]);
                }
                else {
                    std::cout << "Bad args." << std::endl;
                    std::cout << "\tUse \n\t`./tool -help|-h` \n\tto get further information" << std::endl;
                    return -1;
                }
            }
        }
    }
    cv::Mat frame;
    hitcrt::myVideoCap videoCap(device, 1280, 720, 60);
    if(saveVideo) {
        cv::VideoWriter video("../out.avi", v4l2_fourcc('M', 'J', 'P', 'G'), 25, cv::Size(1280, 720));
        while(true) {
            videoCap.VideoGrab(frame);
            cv::imshow("s", frame);
            int key = cv::waitKey(1);
            video.write(frame);
            if(key != -1) {
                break;
            }
        }
    }
    if(saveFrames) {
        int id = 0;
        while(true) {
            videoCap.VideoGrab(frame);
            cv::imshow("s", frame);
            int key = cv::waitKey(1);
            if(saveFrames) {
                sprintf(device, "../f/%d.jpg", id);
                std::cout << device << std::endl;
                id++;
                cv::imwrite(device, frame);
            }
            if(key != -1) {
                break;
            }
        }
    }
    return 0;
}